﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using GameServer.Tools;
using GameServer.Plugins;

namespace GameServer
{
    public class Server
    {
        public static TcpListener ServerSocket;
        public List<Client> Clients = new List<Client>();
        public static Configuration MainConf;
        private PluginManager PlugMan = new PluginManager();
        public static StreamWriter LogWriter = new StreamWriter("server.log", true);

        public static void Main(string[] args)
        {
            new Server();
        }

        public Server()
        {
            try
            {
                Logger.Log(LevelType.INFO, "Initializing server...");
                MainConf = new Configuration("server.properties");
                MainConf.Load();
                Logger.Log(LevelType.INFO, "Configuration loaded, loading plugins...");
                //PlugMan.Reload();
                Logger.Log(LevelType.INFO, "Initializing networking...");

                ServerSocket = new TcpListener(IPAddress.Parse(MainConf.getString("ip-address")), MainConf.getInt("port"));
                ServerSocket.Start();

                ClientListener cl = new ClientListener(ServerSocket, this);

                Logger.Log(LevelType.INFO, "Now listening on " + ServerSocket.LocalEndpoint.ToString());

                new Thread(new ThreadStart(cl.run)).Start();

                Logger.Log(LevelType.INFO, "Ready, now accepting connections.");
            }
            catch (Exception e)
            {
                Logger.Log(LevelType.CRITICAL, e.ToString());
            }
        }

        public Configuration GetConfiguration()
        {
            return MainConf;
        }

        public Server GetServer()
        {
            return this;
        }

        public PluginManager GetPluginManager()
        {
            return PlugMan;
        }
    }
}
